<!-- 订单管理 -->
 <!-- 会员中心 -->
<template>
  <div class="order-management">   
        <!-- 添加空状态提示 -->
        <el-empty v-if="filteredOrders.length === 0" description="暂无订单数据" />

        <el-table v-else :data="pagedOrders" style="width: 100%">
          <el-table-column prop="orderTime" label="下单时间" width="180"></el-table-column>
          <el-table-column prop="orderId" label="订单号" width="180"></el-table-column>
          <el-table-column label="商品信息">
            <template #default="scope">
              <div v-if="scope.row" class="product-info">
                <img
                  :src="scope.row.productImage || 'https://via.placeholder.com/60'"
                  alt="商品图片"
                  class="product-image"
                />
                <div class="product-details">
                  <p>{{ scope.row.productName || '未命名商品' }}</p>
                  <small>
                    颜色：{{ scope.row.color || '默认' }}
                    尺码：{{ scope.row.size || '均码' }}
                    数量：{{ scope.row.quantity || 1 }}
                  </small>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row" :type="statusTagType(scope.row.status)">
                {{ statusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" label="金额" width="120">
            <template #default="scope">
              ¥{{ scope.row ? scope.row.totalPrice.toFixed(2) : '0.00' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <div v-if="scope.row">
                <el-button
                  v-if="scope.row.status === 'pendingPayment'"
                  type="danger"
                  @click="handlePay(scope.row.id)"
                >付款 {{ formatRemainingTime(scope.row.remainingTime) }}</el-button>
                <el-button
                  v-if="scope.row.status === 'pendingShipping'"
                  type="primary"
                  @click="handleConfirmReceipt(scope.row.id)"
                >确认收货</el-button>
                <el-button
                  v-if="['pendingPayment', 'pendingShipping'].includes(scope.row.status)"
                  type="warning"
                  @click="handleCancelOrder(scope.row.id)"
                >取消订单</el-button>
                <el-button
                  type="text"
                  @click="handleViewDetails(scope.row.id)"
                >查看详情</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
          v-if="filteredOrders.length > pageSize"
          class="pagination"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="filteredOrders.length"
          @current-change="handlePageChange"
        ></el-pagination>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
// import { getOrderList } from '@/api/order'
const router = useRouter()
// 订单管理逻辑
const activeTab = ref('all')
const allOrders = ref([])
const filteredOrders = ref([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

const cancelTokenSource = axios.CancelToken.source()
const isComponentMounted = ref(true)

const statusMap = {
  pendingPayment: '待付款',
  pendingShipping: '待发货',
  pendingReceipt: '待收货',
  pendingReview: '待评价',
  paid: '已付款',
  shipped: '已发货',
  received: '已收货',
  completed: '已完成',
  cancelled: '已取消'
}



const statusTagType = (status) => {
  const types = {
    pendingPayment: 'danger',
    pendingShipping: 'warning',
    pendingReceipt: 'primary',
    pendingReview: 'info',
    paid: 'success',
    shipped: '',
    received: 'success',
    completed: 'success',
    cancelled: 'info'
  }
  return types[status] || ''
}

const API_URLS = {
  GET_ORDERS: '/api/orders',
  PAY_ORDER: '/api/orders/:orderId/pay',
  CANCEL_ORDER: '/api/orders/:orderId/cancel',
  CONFIRM_RECEIPT: '/api/orders/:orderId/confirm-receipt',
  VIEW_DETAILS: '/api/orders/:orderId/details'
}

const fetchOrders = async () => {
  try {
    const response = await axios.get(API_URLS.GET_ORDERS, {
      cancelToken: cancelTokenSource.token
    })

    if (!isComponentMounted.value) return

    allOrders.value = response.data.map(o => ({
      id: o.id || Date.now().toString(),
      orderId: o.orderId || `ORDER_${Date.now()}`,
      orderTime: o.orderTime ? dayjs(o.orderTime).format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss'),
      productImage: o.productImage || 'https://via.placeholder.com/60',
      productName: o.productName || '未命名商品',
      color: o.color || '默认',
      size: o.size || '均码',
      quantity: o.quantity || 1,
      status: o.status || 'pendingPayment',
      totalPrice: o.totalPrice || 0,
      remainingTime: o.remainingTime || 1800
    }))
    filterOrders()
  } catch (error) {
    if (axios.isCancel(error)) {
      console.log('请求已取消', error.message)
      return
    }
    console.error('获取订单失败:', error)
    ElMessage.error('获取订单数据失败')
  }
}

const handleSearch = () => {
  currentPage.value = 1
  filterOrders()
}

const filterOrders = () => {
  let result = [...allOrders.value]

  if (activeTab.value !== 'all') {
    result = result.filter(o => o.status === activeTab.value)
  }

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(o =>
      (o.orderId && o.orderId.toLowerCase().includes(keyword)) ||
      (o.productName && o.productName.toLowerCase().includes(keyword))
    )
  }

  result = result.filter(item => item != null)

  filteredOrders.value = result
}

const handlePay = async (orderId) => {
  try {
    await axios.post(API_URLS.PAY_ORDER.replace(':orderId', orderId), {}, {
      cancelToken: cancelTokenSource.token
    })

    if (!isComponentMounted.value) return

    const order = allOrders.value.find(o => o.id === orderId)
    if (order) {
      order.status = 'paid'
      filterOrders()
      ElMessage.success('支付成功')
    }
  } catch (error) {
    if (axios.isCancel(error)) return
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请重试')
  }
}

const handleCancelOrder = async (orderId) => {
  try {
    await axios.delete(API_URLS.CANCEL_ORDER.replace(':orderId', orderId), {
      cancelToken: cancelTokenSource.token
    })

    if (!isComponentMounted.value) return

    allOrders.value = allOrders.value.filter(o => o.id !== orderId)
    filterOrders()
    ElMessage.success('订单已取消')
  } catch (error) {
    if (axios.isCancel(error)) return
    console.error('取消失败:', error)
    ElMessage.error('取消订单失败')
  }
}

const handleConfirmReceipt = async (orderId) => {
  try {
    await axios.put(API_URLS.CONFIRM_RECEIPT.replace(':orderId', orderId), {}, {
      cancelToken: cancelTokenSource.token
    })

    if (!isComponentMounted.value) return

    const order = allOrders.value.find(o => o.id === orderId)
    if (order) {
      order.status = 'received'
      filterOrders()
      ElMessage.success('确认收货成功')
    }
  } catch (error) {
    if (axios.isCancel(error)) return
    console.error('确认失败:', error)
    ElMessage.error('确认收货失败')
  }
}

const handleViewDetails = (orderId) => {
  router.push({ name: 'OrderDetails', params: { id: orderId } })
}

const statusText = (status) => {
  return statusMap[status] || status
}

const formatRemainingTime = (seconds) => {
  if (!seconds) return ''
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

const handlePageChange = (page) => {
  currentPage.value = page
}

const pagedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredOrders.value.slice(start, end)
})

onMounted(() => {
  isComponentMounted.value = true
  fetchOrders()
})

onUnmounted(() => {
  isComponentMounted.value = false
  cancelTokenSource.cancel('组件已卸载，取消所有请求')
})
</script>

<style scoped>
.order-management {
  display: flex;
  flex-direction: column;
  padding: 20px;
  position: relative;
  min-height: 80vh;
}

.search-bar {
  margin: 20px 0;
  width: 400px;
  z-index: 10;
}

.layout-container {
  display: flex;
  margin-top: 20px;
}

.el-aside {
  width: 200px;
  min-height: 600px;
  overflow-y: auto;
  border-right: 1px solid #e6e6e6;
  background-color: #f8f8f8;
}

.el-main {
  flex: 1;
  padding: 0 20px 20px 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-left: 20px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #eee;
}

.product-details {
  display: flex;
  flex-direction: column;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-tabs {
  margin-bottom: 20px;
}

.el-table {
  margin-bottom: 20px;
}
</style>